export function chunkArray(arr: any[] = [], chunkSize = 200) {
  const result = [];
  const len = arr.length;

  // 循环分块
  for (let i = 0; i < len; i += chunkSize) {
    result.push(arr.slice(i, i + chunkSize));
  }

  return result;
}

export function sendMessage<T>(message: any): Promise<T> {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(message, resolve);
  });
}

// 异步执行函数
export async function executeSequentially(asyncFunctions: any[]) {
  // 遍历异步函数数组，使用索引判断位置
  for (let index = 0; index < asyncFunctions.length; index++) {
    const asyncFunc = asyncFunctions[index];
    try {
      // 执行当前异步函数
      await asyncFunc();

      // 检查是否为最后一个函数（通过索引判断）
      // 如果不是最后一个，添加随机延迟
      if (index !== asyncFunctions.length - 1) {
        // 生成0.5-1秒之间的随机延迟时间(毫秒)
        const delayMs = 600 + Math.random() * 500;
        await new Promise((resolve) => setTimeout(resolve, delayMs));
      }
    } catch (error) {
      // 如果有函数执行失败，返回reject
      return Promise.reject(error);
    }
  }

  // 所有函数都执行成功
  return Promise.resolve();
}

export function awaitDelayTime(delayMs = 500) {
  return new Promise((resolve) => setTimeout(resolve, delayMs));
}

export function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// 根据商品采购价格✖(最小倍率~最大倍率),从中找到符合降幅条件的价格填入
export function calculateMaxInputAmountOptimized({
  currencyPrice,
  reduceRateRange,
  purchasePrice,
  multiplierMinInput,
  multiplierMaxInput,
}: {
  currencyPrice: number;
  reduceRateRange: { min: number; max: number };
  purchasePrice: number;
  multiplierMinInput: number;
  multiplierMaxInput: number;
}): number {
  // 基于倍率的金额范围
  const minAmount = purchasePrice * multiplierMinInput;
  const maxAmount = purchasePrice * multiplierMaxInput;
  if (minAmount > maxAmount) return 0;

  const { min: minReduceRate, max: maxReduceRate } = reduceRateRange;

  // 根据降幅范围反推出允许金额范围
  // reduceRate = (currencyPrice - amount) / currencyPrice
  const allowedMin = currencyPrice * (1 - maxReduceRate); // 最小允许金额
  const allowedMax = currencyPrice * (1 - minReduceRate); // 最大允许金额

  // 四舍五入到两位小数，避免浮点误差
  const round2 = (v: number) => Math.round(v * 100) / 100;

  // 向上取 allowedMin（确保不超过最大降幅）
  const allowedMinRounded = Math.ceil(allowedMin * 100) / 100;
  // 向下取 allowedMax（确保不低于最小降幅）
  const allowedMaxRounded = Math.floor(allowedMax * 100) / 100;

  // 计算最终交集区间
  const intersectionMin = Math.max(minAmount, allowedMinRounded);
  const intersectionMax = Math.min(maxAmount, allowedMaxRounded);

  // 如果无交集则返回 0
  if (intersectionMax < intersectionMin) return 0;

  // 在交集范围内，最大可用金额就是 intersectionMax
  return round2(intersectionMax);
}

// 转换为时间戳（秒）
export function parseDateTimeToTs(dateStr: string) {
  // 替换空格为T，兼容Safari和老浏览器
  return Math.floor(new Date(dateStr.replace(" ", "T")).getTime() / 1000);
}

// 将时间戳（秒）转换为 YYYY-MM-DD HH:mm:ss 格式
export function formatTsToDateTime(timestamp: number) {
  const date = new Date(timestamp * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 将时间戳（秒）转换为 YYYY-MM-DD HH:mm:ss 格式
export function getCurrentTimeText() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}
